#include "repomanifestsdirectorymainwindow.h"
#include "ui_repomanifestsdirectorymainwindow.h"

#include <QDir>
#include <QFileDialog>
#include <QJsonArray>
#include <QProcess>
#include <QStandardPaths>

#include <src/utils/repoutil.h>

RepoManifestsDirectoryMainWindow::RepoManifestsDirectoryMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::RepoManifestsDirectoryMainWindow)
{
    ui->setupUi(this);

#ifdef QT_DEBUG
    char* repo = getenv("DEBUG_REPO");
    ui->repo_dir->setText(repo);
    on_repo_dir_returnPressed();
#endif

    QFont font = this->font();
    font.setFamily("Mono");
    ui->show_json->setFont(font);
    ui->show_directory->setFont(font);
}

RepoManifestsDirectoryMainWindow::~RepoManifestsDirectoryMainWindow()
{
    delete ui;
}

QString generate_markdown_nodes(const QJsonArray& projects) {
    struct DNode {
        QMap<QString, DNode> children;
        bool hasProject = false;
    } root;

    // 构建目录树
    for (const auto& p : projects) {
        QJsonObject project = p.toObject();
        QString path = project["path"].toString();

        // 特殊标记构建脚本
        if (project.contains("linkfile")) {
            path += " (with linkfile)";
        }

        QStringList parts = path.split('/');
        DNode* current = &root;

        for (const QString& part : parts) {
            if (!current->children.contains(part)) {
                current->children[part] = DNode();
            }
            current = &current->children[part];
        }
        current->hasProject = true;
    }

    // 递归生成树形结构
    QStringList lines;
    std::function<void(const DNode&, QString, QString)> traverse;

    traverse = [&](const DNode& node, QString prefix, QString indent) {
        const int count = node.children.size();
        int index = 0;

        for (auto it = node.children.begin(); it != node.children.end(); ++it, ++index) {
            bool isLast = (index == count - 1);
            QString connector = isLast ? "└── " : "├── ";

            lines << prefix + connector + it.key();

            if (!it->children.isEmpty() || it->hasProject) {
                QString newPrefix = indent + (isLast ? "    " : "│   ");
                traverse(*it, newPrefix, newPrefix);
            }
        }
    };

    traverse(root, "", "");
    return "```\n" + lines.join("\n") + "\n```";
}

void RepoManifestsDirectoryMainWindow::on_repo_dir_returnPressed()
{
    auto dir = ui->repo_dir->text();

    if (!QDir(ui->repo_dir->text()).exists())
        return;

//    QProcess process;
//    process.setWorkingDirectory(ui->repo_dir->text());
//    process.start("repo manifest --json");
//    process.waitForFinished();
//    process.readAllStandardOutput();

    ui->show_json->setText(RepoUtil::manifest_json_document(dir).toJson());


    auto object = RepoUtil::manifest_json_object(dir);
//    test_dir_node(object.value("project").toArray());
    auto array = object.value("project").toArray();
    ui->show_directory->setText(generate_markdown_nodes(array));
}


void RepoManifestsDirectoryMainWindow::on_open_clicked()
{
    auto dir = QFileDialog::getExistingDirectory(this, "打开", QStandardPaths::writableLocation(QStandardPaths::HomeLocation));
    ui->repo_dir->setText(dir);
    on_repo_dir_returnPressed();
}

